import pygame
import os

class SoundManager:
    def __init__(self):
        """初始化声音管理器"""
        self.sounds = {}
        self.current_music = None
        self.sound_enabled = True
        self.music_enabled = True
        
        # 确保音频系统已初始化
        if not pygame.mixer.get_init():
            pygame.mixer.init()
            
    def load_sound(self, name, path):
        """加载音效
        
        Args:
            name (str): 音效的标识名
            path (str): 音效文件路径
        """
        try:
            self.sounds[name] = pygame.mixer.Sound(path)
        except pygame.error as e:
            print(f"警告：无法加载音效 {path}: {e}")
            
    def play_sound(self, name):
        """播放音效
        
        Args:
            name (str): 要播放的音效的标识名
        """
        if not self.sound_enabled:
            return
            
        if name in self.sounds:
            self.sounds[name].play()
            
    def load_music(self, path):
        """加载背景音乐
        
        Args:
            path (str): 音乐文件路径
        """
        try:
            pygame.mixer.music.load(path)
            self.current_music = path
        except pygame.error as e:
            print(f"警告：无法加载音乐 {path}: {e}")
            
    def play_music(self, loops=-1):
        """播放背景音乐
        
        Args:
            loops (int): 循环次数，-1表示无限循环
        """
        if not self.music_enabled:
            return
            
        try:
            pygame.mixer.music.play(loops)
        except pygame.error as e:
            print(f"警告：无法播放音乐: {e}")
            
    def stop_music(self):
        """停止背景音乐"""
        pygame.mixer.music.stop()
        
    def pause_music(self):
        """暂停背景音乐"""
        pygame.mixer.music.pause()
        
    def unpause_music(self):
        """恢复背景音乐"""
        pygame.mixer.music.unpause()
        
    def set_music_volume(self, volume):
        """设置背景音乐音量
        
        Args:
            volume (float): 音量值（0.0到1.0）
        """
        pygame.mixer.music.set_volume(max(0.0, min(1.0, volume)))
        
    def set_sound_volume(self, name, volume):
        """设置特定音效的音量
        
        Args:
            name (str): 音效的标识名
            volume (float): 音量值（0.0到1.0）
        """
        if name in self.sounds:
            self.sounds[name].set_volume(max(0.0, min(1.0, volume)))
            
    def toggle_sound(self):
        """切换音效开关"""
        self.sound_enabled = not self.sound_enabled
        
    def toggle_music(self):
        """切换背景音乐开关"""
        self.music_enabled = not self.music_enabled
        if self.music_enabled:
            self.unpause_music()
        else:
            self.pause_music()